package cn.source.common.utils.sms;

import cn.source.common.utils.CheckSumBuilder;
import cn.source.common.utils.http.HttpUtils;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 云信短信接口
 * @author: zy
 * @date: 2021年03月30日 11:43
 */
public class DySmsUtil {

    private final static Logger logger= LoggerFactory.getLogger(DySmsUtil.class);

//    public static boolean sendSms(String phone, JSONObject paramJson,String accessKeyId
//            ,String accessKeySecret,String accessKeyTemplate){
//        boolean result = true;
//        String url = "https://api.netease.im/sms/sendcode.action";
//        try {
//            String str = HttpUtils.sendPost(url,
//                    "ac=send&uid=" +accessKeyId+
//                            "&pwd=" +accessKeySecret+
//                            "&template=" +accessKeyTemplate+
//                            "&mobile="+phone+"&content="+paramJson);
//            logger.info("短信接口返回的数据----------------"+str);
//        }catch (Exception e){
//            result = true;
//            logger.info("短信接口返回异常----------------"+e.getMessage());
//        }
//        return result;
//    }

    public static boolean sendSms(String phone,String authCode,String accessKeyId
            ,String accessKeySecret,String accessKeyTemplate){
        boolean result = true;
        String url = "https://api.netease.im/sms/sendcode.action";

        SecureRandom secureRandom = new SecureRandom();
        byte[] randomBytes= new byte[16];
        secureRandom.nextBytes(randomBytes);
        String Nonce = Base64.getEncoder().encodeToString(randomBytes);

        CheckSumBuilder checkSumBuilder = new CheckSumBuilder();
        String CurTime = String.valueOf(new Date().getTime()/1000);

        String CheckSum = checkSumBuilder.getCheckSum(accessKeySecret,Nonce,CurTime);

        try {
            String urlPath = url+"?mobile="+phone+"&templateid="+accessKeyTemplate+"&authCode="+authCode;

            Map<String,String> headerMap = new HashMap<>();
            headerMap.put("AppKey",accessKeyId);
            headerMap.put("Nonce",Nonce);
            headerMap.put("CurTime",CurTime);
            headerMap.put("CheckSum",CheckSum);

            String str = HttpUtils.sendPost(urlPath,headerMap);
            logger.info("短信接口返回的数据----------------"+str);
        }catch (Exception e){
            result = true;
            logger.info("短信接口返回异常----------------"+e.getMessage());
        }
        return result;
    }

    public static void main(String[] args) {
//        JSONObject obj = new JSONObject();
//        obj.put("code", "1234");
//        sendSms("18720989281", obj,null,null,null);
    }
}
